package com.example.service.impl;

import com.alibaba.fastjson2.JSON;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.DownloadUrl;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.example.config.QiniuConfig;
import com.example.service.FileService;
import com.example.vo.FileUploadVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Resource
    private QiniuConfig qiniuConfig;

    @Override
    public FileUploadVO upload(MultipartFile file) {
        FileUploadVO fileUploadVO = new FileUploadVO();
        try{
            //1、 获取凭证
            Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
            //2、 获取上传凭证
            String uploadToken = auth.uploadToken(qiniuConfig.getBucket());
            //4、 配置所在区域
            Configuration cfg = new Configuration(Region.autoRegion());
            //3、 上传管理工具
            UploadManager uploadManager = new UploadManager(cfg);
            //6、 补全参数
            InputStream inputStream = file.getInputStream();
//            String newFileName="1.png";
            // 默认不指定key的情况下，以文件内容的hash值作为文件名 时间日期前缀
            // 获取file的地址
            String originalFilename = file.getOriginalFilename();
            // file扩展名 extendFileName
            String extendFileName = originalFilename.substring(originalFilename.lastIndexOf("."));

            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd/");
            String newFileName=currentDate.format(formatter) + UUID.randomUUID().toString().replace("-", "") + extendFileName;
            log.info("newFileName:{}",newFileName);
            //5、 上传
            Response res = uploadManager.put(inputStream, newFileName, uploadToken, null, null);
//            String s = res.bodyString();
            DefaultPutRet defaultPutRet = JSON.parseObject(res.bodyString(), DefaultPutRet.class); //alibaba

            //todo 需要获取一个正确的url
//            fileUploadVO.setUrl(qiniuConfig.getPrefixUrl()+defaultPutRet.key);
//            System.out.println(s);
//            log.info("res:{}",res);
            DownloadUrl url = new DownloadUrl(qiniuConfig.getPrefixUrl(),false,newFileName);
            long deadline = System.currentTimeMillis() + 3600000L;
            auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
            String urlStr = url.buildURL(auth, deadline);
            fileUploadVO.setUrl(urlStr);
        }
        catch (Exception e){
            e.printStackTrace();
        }

        return fileUploadVO;
    }
}
